import { defineStore } from 'pinia';
import axios from 'axios';

export const usePatientStore = defineStore('patient', {
  state: () => ({
    patients: [],
    currentPatient: null,
    isLoading: false,
    error: null
  }),
  
  actions: {
    async fetchPatients() {
      this.isLoading = true;
      this.error = null;
      
      try {
        // 调用后端API获取患者列表
        const response = await axios.get('http://localhost:3001/api/patients');
        this.patients = response.data;
        return this.patients;
      } catch (error) {
        this.error = error.message;
        // 如果API调用失败，使用模拟数据
        this.patients = [
          { id: 1, name: '张三', age: 45, gender: '男', idCard: '110101197501010011' },
          { id: 2, name: '李四', age: 32, gender: '女', idCard: '110101199001010022' },
          { id: 3, name: '王五', age: 56, gender: '男', idCard: '110101196501010033' }
        ];
        return this.patients;
      } finally {
        this.isLoading = false;
      }
    },
    
    async addPatient(patientData) {
      this.isLoading = true;
      this.error = null;
      
      try {
        // 调用后端API添加患者
        const response = await axios.post('http://localhost:3001/api/patients', patientData);
        this.patients.push(response.data);
        return response.data;
      } catch (error) {
        this.error = error.message;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    
    setCurrentPatient(patient) {
      this.currentPatient = patient;
    }
  }
});